package com.example.http;

import com.sun.deploy.security.CertificateHostnameVerifier;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.conn.ssl.DefaultHostnameVerifier;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.ssl.TrustStrategy;
import org.apache.http.util.EntityUtils;
import org.junit.Test;

import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.net.URISyntaxException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Author：wlz
 * @Package：com.example.http
 * @Project：redis
 * @name：HttpClientDemo
 * @Date：2023/6/3 19:10
 * @Filename：HttpClientDemo
 */
public class HttpClientDemo {

    public void getRequest(String url) throws URISyntaxException, IOException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
        //创建httpClient实例
        CloseableHttpClient client = createHttpClient();
        CloseableHttpClient client1 = HttpClients.createDefault();
        //创建一个uri对象
        URIBuilder uriBuilder = new URIBuilder(url);
        //塞入form参数
        uriBuilder.addParameter("account", "123");
        uriBuilder.addParameter("password", "123");
        //创建httpGet远程连接实例,这里传入目标的网络地址
        HttpGet httpGet = new HttpGet(uriBuilder.build());
        // 设置请求头信息，鉴权(没有可忽略)
        httpGet.setHeader("Authorization", "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0");
        // 设置配置请求参数(没有可忽略)
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// 连接主机服务超时时间
                .setConnectionRequestTimeout(35000)// 请求超时时间
                .setSocketTimeout(60000)// 数据读取超时时间
                .build();
        // 为httpGet实例设置配置
        httpGet.setConfig(requestConfig);
        //执行请求
        CloseableHttpResponse response = client.execute(httpGet);
        //获取Response状态码
        int statusCode = response.getStatusLine().getStatusCode();
        System.out.println(statusCode);
        //获取响应实体, 响应内容
        HttpEntity entity = response.getEntity();
        //通过EntityUtils中的toString方法将结果转换为字符串
        String str = EntityUtils.toString(entity);
        System.out.println(str);
        response.close();
        client.close();
    }

    @Test
    public void test() throws URISyntaxException, IOException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
        String url = "https://47.52.77.204/";
        getRequest(url);
    }

    @Test
    public void test1() throws URISyntaxException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
        Date time = new Date(); // 获取当前时间
        String format = sdf.format(time);// 格式化时间

        // 时间转换为时间戳
        // getTime返回自1970年01月01日00时00分00秒(北京时间1970年01月01日08时00分00秒)起至现在的总毫秒数.
        // 时间戳是指自1970年01月01日00时00分00秒(北京时间1970年01月01日08时00分00秒)起至现在的总秒数
        // 单位换算：1秒=1000毫秒
        long timestamp = time.getTime() / 1000L;
        System.out.println("当前时间："+time);
        System.out.println("当前时间（格式化）："+format);
        System.out.println("当前时间戳："+timestamp);


        // 时间戳转化为时间
        Date time2 = new Date(timestamp * 1000L);
        String time3 = sdf.format(time2);
        System.out.println("时间戳转换来的时间："+time2);
        // 这里会有精度损失，是因为时间戳是秒数
        System.out.println("格式化后的转换时间："+time3);

    }

    private CloseableHttpClient createHttpClient() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
        SSLContext sslcontext = SSLContexts.custom()
                .loadTrustMaterial(null, new ssl())
                .build();

        //                .loadTrustMaterial(null, (chain, authType) -> true)

        SSLConnectionSocketFactory sslSf = new SSLConnectionSocketFactory(sslcontext, null, null,
                new NoopHostnameVerifier());

        return HttpClients.custom().setSSLSocketFactory(sslSf).build();
    }


    static class ssl implements TrustStrategy{

        @Override
        public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
            for (X509Certificate x:x509Certificates) {
                System.out.println("---------------"+x.getNotAfter());
                long time = x.getNotAfter().getTime();
                System.out.println(time);
                System.out.println(System.currentTimeMillis());
            }
            return true;
        }
    }
}
//(如果用try catch 记得关闭资源)